#include "zmqtcpsub.h"
#include <cassert>
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include "zmq.h"

using namespace std;
ZmqTcpSub::ZmqTcpSub(std::string ip, std::string port)
{    
    // 1.初始化上下文
    context = zmq_ctx_new();
 
    // 2.创建套接字、连接发布者
    subscriber = zmq_socket(context, ZMQ_SUB);
    assert(subscriber != NULL);
    std::string addr("tcp://" + ip + ':' + port);
    int rc = zmq_connect(subscriber, addr.c_str());
    assert(rc == 0);
}

ZmqTcpSub::~ZmqTcpSub()
{
    zmq_close(subscriber);
    zmq_ctx_destroy(context);
}

char *s_recv(void *socket)
{
    // 创建zmq_msg_t对象接收数据
    zmq_msg_t msg;
    zmq_msg_init(&msg);
    int size = zmq_msg_recv(&msg, socket, 0);
    if(size == -1)
    {
        return NULL;
    }
 
    // 将zmq_msg_t对象中的数据保存到字符串中
    char *string = (char*)malloc(size + 1);
    memcpy(string, zmq_msg_data(&msg), size);
 
    zmq_msg_close(&msg);
    string[size] = 0;
 
    return string;
}

std::string ZmqTcpSub::sub(std::string&& channel)
{
    int rc = 0;
    channel = '['+channel+']';
    rc = zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, channel.c_str(), channel.length());
    std::cout << zmq_strerror(errno) << std::endl;
 
    std::string sMsg(s_recv(subscriber));
    return sMsg;
}

int main(int argc, char const *argv[])
{
    ZmqTcpSub subscriber("127.0.0.1", "9776");
    while(true)
    {
        cout << "listening..." << endl;
        subscriber.sub("debug");
    }
    return 0;
}
